package com.woniuxy.ptapp.app.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.woniuxy.commons.exception.MyException;
import com.woniuxy.commons.util.*;
import com.woniuxy.moneyapp.client.ReturnCashClient;
import com.woniuxy.ptapp.common.param.LoginUser;
import com.woniuxy.ptapp.common.util.FinAccountIdByMessageId;
import com.woniuxy.ptapp.common.util.FinMessageIdByAccountId;
import com.woniuxy.ptapp.common.util.GetLogingUser;
import com.woniuxy.ptapp.client.AppealClient;
import com.woniuxy.ptapp.client.param.FileUploadDto;
import com.woniuxy.ptapp.client.param.ShowAllAppealDto;
import com.woniuxy.ptapp.common.config.OssConfig;
import com.woniuxy.ptapp.common.exception.EnumExceptionCode;
import com.woniuxy.ptapp.common.exception.ParamException;
import com.woniuxy.ptapp.common.exception.WoniuxyException;
import com.woniuxy.ptapp.infra.model.AppealInfo;
import com.woniuxy.ptapp.infra.model.ClassesOrder;
import com.woniuxy.ptapp.service.AppealInfoService;
import com.woniuxy.ptapp.service.ClassesOrderService;
import com.woniuxy.ptapp.service.dto.AppealDto;
import com.woniuxy.relation.client.AnnouncementClient;
import com.woniuxy.relation.client.form.SendAnnouncementForm;
import com.woniuxy.userapp.client.FrontAccountClient;
import com.woniuxy.userapp.client.StudentClient;
import com.woniuxy.userapp.client.param.AutoDeductMoneyInfo;
import com.woniuxy.userapp.client.param.StudentInfo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangdong
 * @since 2022-07-30
 */
@RestController
public class AppealInfoController implements AppealClient {
    @Resource
    private GetLogingUser getLogingUser;
    @Resource
    private AppealInfoService appealInfoService;
    @Resource
    private OssConfig ossConfig;
    @Resource
    private ClassesOrderService classesOrderService;
    @Resource
    private FinMessageIdByAccountId findUtil;
    @Resource
    private FrontAccountClient frontAccountClient;
    @Resource
    private FinAccountIdByMessageId findAccountId;
    @Resource
    private AnnouncementClient ac;
    @Resource
    private ReturnCashClient returnCashClientl;

    public Result startAppeal(Integer complaintOrderClassesId, String complaintReason,String complaintVoucher) {
        if ( complaintOrderClassesId == null || complaintReason == null || complaintOrderClassesId <= 0 ||complaintReason == "") {
            throw new ParamException();
        }
        LoginUser logingUser = getLogingUser.getLogingUser();
        //判断订单id是否属于该登录用户
        Integer studentId = findUtil.findStudentId(logingUser.getLoginId());
        QueryWrapper<ClassesOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",complaintOrderClassesId);
        queryWrapper.eq("student_id",studentId);
        ClassesOrder one = classesOrderService.getOne(queryWrapper);
        if(null==one){
            throw new WoniuxyException(EnumExceptionCode.ClaessIdWrong.getCode(),EnumExceptionCode.ClaessIdWrong.getMessage() );
        }
        //一个订单只能审核一次
        AppealInfo appealInfo = appealInfoService.getOne(new QueryWrapper<AppealInfo>().eq("complaint_order_classes_id", complaintOrderClassesId));
        if(appealInfo!=null){
           throw new WoniuxyException(EnumExceptionCode.OrderCanOnlyAppealAgain.getCode(),EnumExceptionCode.OrderCanOnlyAppealAgain.getMessage() );
        }
        AppealDto appealDto = new AppealDto();
        appealDto.setComplaintMan(logingUser.getLoginName());
        appealDto.setComplaintManId(studentId);
        appealDto.setComplaintOrderClassesId(complaintOrderClassesId);
        appealDto.setComplaintVoucher(complaintVoucher);
        appealDto.setComplaintReason(complaintReason);
        appealDto.setComplaintTime(DateUtil.timeFormatString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
        appealInfoService.startAppeal(appealDto);
        return Result.getInstance().setMsg("提交申诉成功");
    }

    @Resource
    JwtUtil jwtUtil;


    public Result adminAudit(Integer classesOrderId, Integer dealReason, BigDecimal punishMoney) throws UnsupportedEncodingException, JsonProcessingException {
        if(dealReason!=1&&dealReason!=2&&dealReason!=0){
            throw new ParamException();
        }
        if(null==classesOrderId||null==dealReason||dealReason<0||classesOrderId<0){
            throw new ParamException();
        }
        LoginUser logingUser = getLogingUser.getLogingUser();

        AppealInfo appealInfo = appealInfoService.getOne(new QueryWrapper<AppealInfo>().eq("complaint_order_classes_id", classesOrderId));
        if(appealInfo==null){
           throw new WoniuxyException(EnumExceptionCode.TheOrderNoAppeal.getCode(),EnumExceptionCode.TheOrderNoAppeal.getMessage());
        }
        if(appealInfo.getComplaintState()!=0){
            throw new MyException(50001,"已经审核,请勿重新审核");
        }
        appealInfo.setAuditorMan(logingUser.getLoginName());
        appealInfo.setAuditorManId(logingUser.getLoginId());
        appealInfo.setAuditorTime(DateUtil.timeFormatString(System.currentTimeMillis(),"yyyy-MM-dd HH:mm:ss"));
        appealInfo.setDealReason(dealReason);
        //通过申诉课程id查询对应的课程订单
        ClassesOrder classesOrder = classesOrderService.getOne(new QueryWrapper<ClassesOrder>().eq("id", classesOrderId));
        if(classesOrder==null){
            throw new WoniuxyException(EnumExceptionCode.getClassesOrderFail.getCode(),EnumExceptionCode.getClassesOrderFail.getMessage());
        }
        Integer studentAccountId = findAccountId.findStudentAccountId(classesOrder.getStudentId());
        Integer venueAccountId = findAccountId.findVenueAccountId(classesOrder.getVenueId());
        //判断处理结果对应的执行操作
        if(dealReason==0){
            //操作退款
            AutoDeductMoneyInfo autoDeductMoneyInfo = new AutoDeductMoneyInfo();
            autoDeductMoneyInfo.setAddId(studentAccountId);
            autoDeductMoneyInfo.setDeductionId(venueAccountId);
            autoDeductMoneyInfo.setMoneyAmount(punishMoney==null?classesOrder.getPrice():punishMoney);
            //订单退款接口
            Result result = frontAccountClient.autoDeductMoney(autoDeductMoneyInfo);
            if(result==null||result.getCode()!=200){
                throw new WoniuxyException(EnumExceptionCode.TheVenueToInsufficient.getCode(),EnumExceptionCode.TheVenueToInsufficient.getMessage() );
            }
            appealInfo.setComplaintState(1);
            //通知学员
            SendAnnouncementForm sendAnnouncementForm = new SendAnnouncementForm();
            sendAnnouncementForm.setContent("尊敬的会员"+appealInfo.getAuditorMan()+"您好,关于您的订单编号"+classesOrder.getOrderNum()+"申诉问题,目前已经审核通过支持到您退款,退款金额会在1-3个工作日退回您的钱包中,感谢您的支持祝您生活愉快");
            sendAnnouncementForm.setAcceptAccountId(studentAccountId+"");
            ac.sendAnnouncement(sendAnnouncementForm);
            //通知场馆
            SendAnnouncementForm sendAnnouncementForm1 = new SendAnnouncementForm();
            sendAnnouncementForm1.setContent(appealInfo.getAuditorMan()+"您好,关于您店铺的订单编号"+classesOrder.getOrderNum()+"会员申诉问题,目前平台专员已经审核通过,支持学员退款处理,请您保持钱包余额充足");
            sendAnnouncementForm1.setAcceptAccountId(venueAccountId+"");
            ac.sendAnnouncement(sendAnnouncementForm1);
        }else if(dealReason==1){
            appealInfo.setComplaintState(2);
            SendAnnouncementForm sendAnnouncementForm = new SendAnnouncementForm();
            sendAnnouncementForm.setContent("尊敬的会员"+appealInfo.getAuditorMan()+"您好,关于您的订单编号"+classesOrder.getOrderNum()+"申诉问题,经过审核专员审核,目前未支持到您的诉求,非常抱歉给你带来不便,感谢您的支持祝您生活愉快");
            sendAnnouncementForm.setAcceptAccountId(studentAccountId+"");
            ac.sendAnnouncement(sendAnnouncementForm);
            //驳回审核
        }else if(dealReason==2){
            //处罚商家
            appealInfo.setComplaintState(1);
            SendAnnouncementForm sendAnnouncementForm = new SendAnnouncementForm();
            sendAnnouncementForm.setContent("尊敬的会员"+appealInfo.getAuditorMan()+"您好,关于您的订单编号"+classesOrder.getOrderNum()+"申诉问题,目前已经审核通过,平台会根据规则对场馆进行处罚,感谢您的支持祝您生活愉快");
            sendAnnouncementForm.setAcceptAccountId(studentAccountId+"");
            ac.sendAnnouncement(sendAnnouncementForm);
            //通知场馆
            SendAnnouncementForm sendAnnouncementForm1 = new SendAnnouncementForm();
            sendAnnouncementForm1.setContent(appealInfo.getAuditorMan()+"您好,关于您店铺的订单编号"+classesOrder.getOrderNum()+"会员申诉问题,目前平台专员已经审核通过,目前已经对您店铺进行处罚扣分,达到12分,会封店铺,请您做好店铺运营！");
            sendAnnouncementForm1.setAcceptAccountId(venueAccountId+"");
            ac.sendAnnouncement(sendAnnouncementForm1);
        }
        boolean b = appealInfoService.saveOrUpdate(appealInfo);
        if(!b){
            throw new WoniuxyException(EnumExceptionCode.AuditFailure.getCode(),EnumExceptionCode.AuditFailure.getMessage());
        }
        return Result.getInstance().setCode(200).setMsg("审核成功");
    }

    public Result<List<FileUploadDto>> uploadFoodVariety(MultipartFile[] upload) throws IOException {
        System.out.println(upload);
        if(upload==null){
            throw new ParamException();
        }
        String time = DateUtil.timeFormatString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
        List<FileUploadDto> fileUploadDtos = new ArrayList<>();
        for (MultipartFile multipartFile : upload) {

            FileUploadDto fileUploadDto = new FileUploadDto();
            //获取上传文件的原始名称
            String originalFilename = multipartFile.getOriginalFilename();
            fileUploadDto.setOldfilename(originalFilename);
            //现在的文件名
            String saveFileName= UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
            fileUploadDto.setFilename(saveFileName);
            //文件上传到阿里云
            String s = ossConfig.fileUpload(saveFileName, multipartFile.getInputStream());
            //后缀名
            fileUploadDto.setFilesuffix(saveFileName.substring(saveFileName.lastIndexOf(".")));
            //文件大小
            fileUploadDto.setSize(multipartFile.getSize());
            fileUploadDto.setFilepath(s);
            fileUploadDto.setCreatedate(time);
            fileUploadDtos.add(fileUploadDto);
        }

        return Result.getInstanceList(FileUploadDto.class).setMsg("上传成功").setData(fileUploadDtos);
    }

    @Override
    public Result<Page<ShowAllAppealDto>> AllAppeal(Integer current,Integer size) {
        Page<AppealInfo> page = new Page<>(current==null?1:current,size==null?5:size);
        Page<AppealInfo> page1 = appealInfoService.page(page);
        if(null==page1){
           throw new WoniuxyException(EnumExceptionCode.getAllAppealFail.getCode(),EnumExceptionCode.getAllAppealFail.getMessage());
        }
        Page<ShowAllAppealDto> showAllAppealDtoPage = BeanCopyUtil.copyPage(page1, ShowAllAppealDto.class);

        return Result.getInstancePage(ShowAllAppealDto.class).setMsg("查询申诉记录成功").setData(showAllAppealDtoPage);
    }

}

